const { Friend } = require('../../../model/friend');
const { User } = require('../../../model/user')
const { decodeToken } = require('../../../middleGuard/jwt.js')

module.exports = async (req, res) => {
  const userId = decodeToken(req.headers.authorization).userId
  const { friend } = req.body
  const current = await Friend.findOne({ friend, user: userId })
  if(!current) {
    // 自动建立双向好友
    // 加入对方的好友
    await Friend.create({ friend: userId, user: friend, createTime: new Date().getTime() })
    // 创建自己的好友
    Friend.create({ friend, user: userId, createTime: new Date().getTime() }).then(async (item) => {
      const currentFriend = await User.findOne({_id: item.friend})
      res.json({
        data: {
          ...item.toObject(),
          friend: currentFriend
        },
        message: '添加成功！'
      })
    }).catch((err) => {
      res.status(403)
      res.json({
        log: err,
        message: '添加失败！'
      })
    })
  } else {
    res.json({
      message: '已存在该聊天对象！'
    })
  }
}